#!/usr/bin/env python3
"""
简化的Mock数据管理器
自动管理测试数据的生成和使用
"""

import json
import os
import random
from datetime import datetime, timedelta
from pathlib import Path

class MockDataManager:
    """Mock数据管理器"""
    
    def __init__(self):
        self.data_file = Path(__file__).parent / "mock_trades.json"
        self.random_seed = 42  # 固定种子确保可重现
    
    def get_mock_data_info(self):
        """获取Mock数据信息"""
        if self.data_file.exists():
            try:
                with open(self.data_file, 'r', encoding='utf-8') as f:
                    data = json.load(f)
                
                file_size = self.data_file.stat().st_size / 1024 / 1024  # MB
                modified_time = datetime.fromtimestamp(self.data_file.stat().st_mtime)
                
                return {
                    "exists": True,
                    "count": len(data),
                    "file_size_mb": round(file_size, 2),
                    "modified_time": modified_time.strftime("%Y-%m-%d %H:%M:%S"),
                    "file_path": str(self.data_file)
                }
            except Exception as e:
                return {
                    "exists": True,
                    "error": f"文件损坏: {str(e)}",
                    "file_path": str(self.data_file)
                }
        else:
            return {
                "exists": False,
                "file_path": str(self.data_file)
            }
    
    def generate_mock_data(self):
        """生成Mock数据"""
        random.seed(self.random_seed)
        
        # 品种配置
        symbols = [
            ("MESM25", 0.75),  # 75%
            ("ESM25", 0.15),   # 15%
            ("MNQM25", 0.10)   # 10%
        ]
        
        # 方向配置
        directions = [
            ("Long", 0.48),    # 48%
            ("Short", 0.52)    # 52%
        ]
        
        # 交易类型配置
        trade_types = [
            ("target", 0.28),    # 28%
            ("scalp", 0.18),     # 18%
            ("swing", 0.20),     # 20%
            ("breakout", 0.17),  # 17%
            ("mr", 0.12),        # 12%
            ("other", 0.05)      # 5%
        ]
        
        # Side配置
        sides = [
            ("Left", 0.50),      # 50%
            ("Right", 0.50)      # 50%
        ]
        
        trades = []
        
        for i in range(100):
            # 选择品种
            symbol = self._weighted_choice(symbols)
            
            # 选择方向
            direction = self._weighted_choice(directions)
            
            # 选择交易类型
            trade_type = self._weighted_choice(trade_types)
            
            # 选择Side
            side = self._weighted_choice(sides)
            
            # 生成价格
            base_price = random.uniform(4000, 6000)
            open_price = round(base_price, 2)
            
            # 生成盈亏 (约49%盈利, 51%亏损)
            is_profitable = random.random() < 0.49
            if is_profitable:
                close_price = open_price + random.uniform(5, 50)
            else:
                close_price = open_price - random.uniform(5, 50)
            
            close_price = round(close_price, 2)
            
            # 生成其他字段
            qty = random.randint(1, 5)
            point_profit = close_price - open_price if direction == "Long" else open_price - close_price
            
            # 计算净利润
            multiplier = 5.0 if symbol == "MESM25" else 20.0  # MESM25: $5/点, ESM25/MNQM25: $20/点
            gross_profit = point_profit * qty * multiplier
            commission = round(random.uniform(2, 5), 2)
            net_profit = round(gross_profit - commission, 2)
            
            # 生成时间
            start_date = datetime(2024, 1, 1)
            random_days = random.randint(0, 365)
            open_datetime = start_date + timedelta(days=random_days, hours=random.randint(0, 23), minutes=random.randint(0, 59))
            close_datetime = open_datetime + timedelta(hours=random.randint(1, 12), minutes=random.randint(0, 59))
            
            trade = {
                "trade_id": 1000000000000000000 + i,
                "symbol": symbol,
                "open_datetime": open_datetime.strftime("%Y-%m-%d %H:%M:%S"),
                "close_datetime": close_datetime.strftime("%Y-%m-%d %H:%M:%S"),
                "open_price": open_price,
                "close_price": close_price,
                "open_qty": qty,
                "close_qty": qty,
                "direction": direction,
                "open_order_type": random.choice(["Market", "Limit"]),
                "trade_type": trade_type,
                "side": side,
                "holding_time": str(close_datetime - open_datetime).split('.')[0],
                "nth_trade": random.randint(1, 10),
                "session": random.choice(["RTH", "ETH"]),
                "point_profit_per_lot": round(point_profit, 2),
                "total_points": round(point_profit * qty, 2),
                "gross_profit": round(gross_profit, 2),
                "net_profit": net_profit,
                "commission": commission,
                "max_floating_profit_points": round(abs(point_profit) + random.uniform(5, 20), 2),
                "max_floating_profit_dollars": round(random.uniform(1000, 8000), 2),
                "max_floating_loss_points": round(random.uniform(5, 30), 2),
                "max_floating_loss_dollars": round(random.uniform(200, 4000), 2),
                "entry_reason": random.choice(["breakout", "pullback", "pattern_completion"]),
                "exit_reason": random.choice(["target_hit", "stop_hit", "time_exit", "market_close"]),
                "stop_loss_price": round(open_price - (20 if direction == "Long" else -20), 2),
                "stop_loss_reason": random.choice(["percentage_based", "atr_based", "support_level", "resistance_level"]),
                "take_profit_price": round(open_price + (100 if direction == "Long" else -100), 2),
                "take_profit_reason": random.choice(["support_level", "resistance_level", "trailing_stop"])
            }
            
            trades.append(trade)
        
        # 保存数据
        with open(self.data_file, 'w', encoding='utf-8') as f:
            json.dump(trades, f, indent=2, ensure_ascii=False)
        
        return True
    
    def _weighted_choice(self, choices):
        """根据权重选择"""
        total = sum(weight for choice, weight in choices)
        r = random.uniform(0, total)
        upto = 0
        for choice, weight in choices:
            if upto + weight >= r:
                return choice
            upto += weight
        return choices[-1][0]  # 备用
    
    def load_mock_data(self):
        """加载Mock数据"""
        if not self.data_file.exists():
            print("📝 Mock数据不存在，正在生成...")
            if self.generate_mock_data():
                print("✅ Mock数据生成完成")
            else:
                print("❌ Mock数据生成失败")
                return None
        
        try:
            with open(self.data_file, 'r', encoding='utf-8') as f:
                return json.load(f)
        except Exception as e:
            print(f"❌ 加载Mock数据失败: {e}")
            return None

def main():
    """主函数 - 显示数据状态"""
    print("Mock数据管理器")
    print("=" * 30)
    
    manager = MockDataManager()
    info = manager.get_mock_data_info()
    
    if info["exists"]:
        if "error" in info:
            print(f"❌ 数据文件存在但有问题: {info['error']}")
            print(f"📁 文件路径: {info['file_path']}")
        else:
            print(f"✅ Mock数据已存在")
            print(f"📊 交易数量: {info['count']} 笔")
            print(f"📁 文件大小: {info['file_size_mb']} MB")
            print(f"🕒 修改时间: {info['modified_time']}")
            print(f"📁 文件路径: {info['file_path']}")
    else:
        print("❌ Mock数据不存在")
        print(f"📁 预期路径: {info['file_path']}")
        print("\n💡 提示: 运行任何测试命令会自动生成数据")
    
    print("\n🔧 可用操作:")
    print("  - 运行测试: python test_simple.py")
    print("  - 重新生成: 删除 mock_trades.json 文件")

if __name__ == '__main__':
    main() 